//
//  UIImage+Aspect.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/11.
//

import SwiftUI

extension UIImage {
    // 根据宽度获取等比例高度
    func proportionalHeight(forWidth width: CGFloat) -> CGFloat {
        let aspectRatio = self.size.height / self.size.width
        return width * aspectRatio
    }
    
    // 根据高度获取等比例宽度
    func proportionalWidth(forHeight height: CGFloat) -> CGFloat {
        let aspectRatio = self.size.width / self.size.height
        return height * aspectRatio
    }
    
    static func compress(_ image: UIImage, maxKB: Int) -> Data? {
        var compression: CGFloat = 1.0
        let maxSize = maxKB * 1024
        var data: Data?

        while compression > 0 {
            data = image.jpegData(compressionQuality: compression)
            if let data = data, data.count <= maxSize {
                return data
            }
            compression -= 0.1
        }
        
        return data
    }
}
